package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.AdUserService;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Override
    public ResponseResult login(AdUserDto adUserDto) {
        //校验参数
        if (adUserDto==null||StringUtils.isBlank(adUserDto.getName())|| StringUtils.isBlank(adUserDto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据用户名去数据库查询
        QueryWrapper<AdUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(AdUser::getName,adUserDto.getName());
        List<AdUser> list = this.list(queryWrapper);
        if (list.size()>0){
            AdUser adUser = list.get(0);
            //用户输入密码+数据库中查出来的盐值 生产一个新的MD5密码串
            String newPwd = DigestUtils.md5DigestAsHex(adUserDto.getPassword().concat(adUser.getSalt()).getBytes());

            //数据库中密码串比较 生成一个新的MD5密码串 如果是true生成token 传到前台
            if (adUser.getPassword().equals(newPwd)){
                //生成token
                Map<String,Object> map=new HashMap<>();
                map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
                adUser.setPassword("");
                adUser.setSalt("");
                map.put("user",adUser);
                return ResponseResult.okResult(map);
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

    }
}
